
#include "../include/ehome.h"
#include "leds.h"
#include "hcsr.h"
#include "beep.h"
#include "mp3_player.h"
#include "step.h"
#include "update.h"
int main(void){
    
    int fd=socket(PF_INET,SOCK_DGRAM,0);
    pthread_t threadID=0;
    //pthread_t threadID1=1;
    char *err=NULL;
    struct sockaddr_in addr;
    struct sockaddr_in fromaddr;
    int len=sizeof(struct sockaddr_in);
    if(fd<0){
      err=strerror(errno);
      pr_debug("get socket failed:%s",err);
      return -1;
    }
    addr.sin_family=PF_INET;
    addr.sin_port=htons(PORT_LEDS);
    addr.sin_addr.s_addr=inet_addr(SERVERIP);
    
    bind(fd,(const struct sockaddr *)&addr,sizeof(addr));
    
    pthread_create(&threadID,NULL,hcsr_thread,NULL);
    pthread_detach(threadID);

    int mma8653_fd=open("/dev/mma865x",O_RDONLY);
   /* pthread_create(&threadID1,NULL,FF_thread,(void *)&mma8653_fd);
    pthread_detach(threadID1);*/
    while(1){
        int cmd=0;
        int ret=0;
        recvfrom(fd,&cmd,sizeof(cmd),0,
                (struct sockaddr *)&fromaddr,
                &len);
        pr_debug("recv cmd is %d\n",cmd);
        if(cmd>=LED_BEDROOM_ON && cmd<= LED_RESTROOM_OFF){
            leds(cmd);
        }else if(cmd>=MUSIC_PLAY && cmd <=MUSIC_PREV){
            mp3(cmd);
        }else if(cmd>=BEEP_ON && cmd<=BEEP_OFF){
            beep(cmd);
        }else if(cmd==IF_MONITOR){
            step(mma8653_fd,fd,(struct sockaddr *)&fromaddr);
        }else if(cmd >=UPDATE_KERNEL && cmd <=UPDATE_CLIENT ){
            ret=update(cmd);
            pr_debug("SERVER:ret is %d",ret);
            sendto(fd,&ret,sizeof(ret),0,(struct sockaddr *)&fromaddr,sizeof(fromaddr));
        }else{
            pr_debug("%s: unknown cmd\n",__func__);
        }
    }
    return 0;
}
